// 任务管理应用
document.addEventListener('DOMContentLoaded', function() {
    // 获取DOM元素
    const taskForm = document.getElementById('addTaskForm');
    const tasksContainer = document.getElementById('tasksContainer');
    const filterButtons = document.querySelectorAll('.filter-btn');
    const completedCountElement = document.getElementById('completedCount');
    
    // 任务数组
    let tasks = JSON.parse(localStorage.getItem('tasks')) || [];
    let currentFilter = 'all';
    
    // 初始化应用
    function initApp() {
        renderTasks();
        updateCompletedCount();
        
        // 添加事件监听器
        taskForm.addEventListener('submit', addTask);
        
        filterButtons.forEach(button => {
            button.addEventListener('click', () => {
                // 移除所有按钮的active类
                filterButtons.forEach(btn => btn.classList.remove('active'));
                // 为当前点击的按钮添加active类
                button.classList.add('active');
                // 更新当前筛选器
                currentFilter = button.dataset.filter;
                // 重新渲染任务
                renderTasks();
            });
        });
    }
    
    // 添加新任务
    function addTask(e) {
        e.preventDefault();
        
        const titleInput = document.getElementById('taskTitle');
        const descriptionInput = document.getElementById('taskDescription');
        const priorityInput = document.getElementById('taskPriority');
        const dueDateInput = document.getElementById('taskDueDate');
        
        const newTask = {
            id: Date.now(),
            title: titleInput.value,
            description: descriptionInput.value,
            priority: priorityInput.value,
            dueDate: dueDateInput.value,
            completed: false,
            createdAt: new Date().toISOString()
        };
        
        tasks.push(newTask);
        saveTasks();
        renderTasks();
        
        // 重置表单
        taskForm.reset();
    }
    
    // 渲染任务列表
    function renderTasks() {
        // 清空容器
        tasksContainer.innerHTML = '';
        
        // 筛选任务
        let filteredTasks = tasks;
        if (currentFilter === 'active') {
            filteredTasks = tasks.filter(task => !task.completed);
        } else if (currentFilter === 'completed') {
            filteredTasks = tasks.filter(task => task.completed);
        }
        
        // 检查是否有任务
        if (filteredTasks.length === 0) {
            const emptyState = document.createElement('div');
            emptyState.className = 'empty-state';
            
            if (currentFilter === 'all') {
                emptyState.innerHTML = '<p>还没有任务，添加一个吧！</p>';
            } else if (currentFilter === 'active') {
                emptyState.innerHTML = '<p>没有待完成的任务</p>';
            } else {
                emptyState.innerHTML = '<p>还没有完成的任务</p>';
            }
            
            tasksContainer.appendChild(emptyState);
            return;
        }
        
        // 渲染任务
        filteredTasks.forEach(task => {
            const taskElement = createTaskElement(task);
            tasksContainer.appendChild(taskElement);
        });
        
        updateCompletedCount();
    }
    
    // 创建任务元素
    function createTaskElement(task) {
        const taskCard = document.createElement('div');
        taskCard.className = `task-card ${task.completed ? 'completed' : ''}`;
        taskCard.dataset.id = task.id;
        
        // 格式化日期
        let dueDateText = '无截止日期';
        if (task.dueDate) {
            const dueDate = new Date(task.dueDate);
            dueDateText = dueDate.toLocaleDateString('zh-CN');
        }
        
        // 优先级文本和类名
        let priorityText = '';
        let priorityClass = '';
        switch(task.priority) {
            case 'high':
                priorityText = '高优先级';
                priorityClass = 'priority-high';
                break;
            case 'medium':
                priorityText = '中优先级';
                priorityClass = 'priority-medium';
                break;
            case 'low':
                priorityText = '低优先级';
                priorityClass = 'priority-low';
                break;
        }
        
        taskCard.innerHTML = `
            <h3>${task.title}</h3>
            <p>${task.description || '无描述'}</p>
            <div class="task-meta">
                <span class="priority ${priorityClass}">${priorityText}</span>
                <span class="due-date">${dueDateText}</span>
            </div>
            <div class="task-actions">
                <button class="complete-btn">${task.completed ? '标记未完成' : '标记完成'}</button>
                <button class="delete-btn">删除</button>
            </div>
        `;
        
        // 添加事件监听器
        const completeBtn = taskCard.querySelector('.complete-btn');
        const deleteBtn = taskCard.querySelector('.delete-btn');
        
        completeBtn.addEventListener('click', () => toggleTaskCompletion(task.id));
        deleteBtn.addEventListener('click', () => deleteTask(task.id));
        
        return taskCard;
    }
    
    // 切换任务完成状态
    function toggleTaskCompletion(taskId) {
        tasks = tasks.map(task => {
            if (task.id === taskId) {
                return { ...task, completed: !task.completed };
            }
            return task;
        });
        
        saveTasks();
        renderTasks();
    }
    
    // 删除任务
    function deleteTask(taskId) {
        if (confirm('确定要删除这个任务吗？')) {
            tasks = tasks.filter(task => task.id !== taskId);
            saveTasks();
            renderTasks();
        }
    }
    
    // 保存任务到localStorage
    function saveTasks() {
        localStorage.setItem('tasks', JSON.stringify(tasks));
    }
    
    // 更新已完成任务计数
    function updateCompletedCount() {
        const completedTasks = tasks.filter(task => task.completed);
        completedCountElement.textContent = completedTasks.length;
    }
    
    // 初始化应用
    initApp();
});